package com.bmslz.monitor.base.config.mp;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.bmslz.monitor.base.CommonConstant;
import com.bmslz.monitor.base.entity.User;
import com.bmslz.monitor.helper.LoginHelper;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class MybatisPlusConfig {
    private static final List<String> splitByUserTables = new ArrayList<>();

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        initSplitByUserTables();
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); // 分页

        // 添加租户处理器
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {

            @Override
            public Expression getTenantId() {
                // 从上下文中获取当前用户ID
                User user = LoginHelper.getUser();
                String userId = "0";
                if (user != null) {
                    userId = LoginHelper.getUser().getId();
                }
                return new LongValue(userId);
            }

            @Override
            public String getTenantIdColumn() {
                // 数据库中的租户字段名
                return "user_id";
            }

            @Override
            public boolean ignoreTable(String tableName) {
                // 如果是不需要隔离的用户，或者表不在隔离列表中，都忽略
                User user = LoginHelper.getUser();
                String userId = "0";
                String role = "";
                if (user != null) {
                    userId = user.getId();
                    role = user.getRole();
                }
                if (userId != null && role.equals(CommonConstant.ROLE_SUPER)) {
                    return true; // 超级管理员不做隔离
                }
                //如果用户id等于-1 或者0 不执行隔离
                if ("-1".equals(userId) || "0".equals(userId)) {
                    return true;
                }
                //如果手动关闭了多租户隔离 也不执行隔离
                if(LoginHelper.getCloseIsolation()!=null && LoginHelper.getCloseIsolation()){
                    return true;
                }
                return !splitByUserTables.contains(tableName);
            }

            @Override
            public boolean ignoreInsert(List<net.sf.jsqlparser.schema.Column> columns, String tenantIdColumn) {
                return columns.stream().anyMatch(column ->
                        column.getColumnName().equalsIgnoreCase(tenantIdColumn));
            }
        }));

        return interceptor;
    }

    /**
     * 初始化需要用户数据隔离的表
     */
    private void initSplitByUserTables() {
        splitByUserTables.add("m_alarm_model");
        splitByUserTables.add("m_monitor_model");
        splitByUserTables.add("m_project");
        splitByUserTables.add("m_project_alarm");
        splitByUserTables.add("m_project_data");
    }
}